<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
namespace Admin\Controller;

use Think\Controller;
use Common\Lib\Util\ToolUtil;
use Admin\Model\AttachmentModel;

/**
 * @author fanyuliang
 */
class UploadController extends Controller{
	
	private $attachmentModel;
	
    public function index(){
        $user_id = session('userId');
    	$allowExts = array('jpg','jpeg','gif','png');
    	$maxSize = -1;
    	//附件类型
    	$type = I('type');
    	$savePath = C('ATTACHMENT_PATH').$type;
    	$image_crop = C('IMAGE_CROP');
    	$thumb = $image_crop[$type];
    	$result = ToolUtil::uploadFile($savePath,$maxSize,$allowExts,$thumb);
    	$uploadInfo = $this->handleAttache($result,$type,$thumb,$user_id);
    	$this->ajaxReturn($uploadInfo);
    }
    
    private function handleAttache($result,$type,$thumb,$user_id){
    	$uploadInfo = array();
    	foreach ($result as $rs) {
	    	$data = array();
	    	$filePath = '/upload/'.$type.$rs['savename'];
	    	$rs['filePath'] = $filePath;
	    	$isImage = in_array($rs['extension'], array('jpg','jpeg','gif','png'));
// 	    	if ($thumb['prefix'] && in_array('small_', explode(',', $thumb['prefix'])) && $isImage) {
// 	    		//返回缩略图
// 	    		$savename = pathinfo($filePath,PATHINFO_BASENAME);
// 	    		$rs['filePath'] = str_replace($savename, 'small_'.$savename, $filePath);
// 	    		$rs['filePath'] = $filePath;
// 	    	}
	    	$attachmentModel = new AttachmentModel();
	    	$data['type'] = $type;
	    	$data['filename'] = $rs['name'];
	    	$data['attachment'] = $filePath;
	    	$data['filesize'] = $rs['size'];
	    	$id = $attachmentModel->saveAttachement($data,$rs['extension'],$user_id);
	    	$uploadInfo[] = array_merge($rs,array('attachement_id' => $id));
    	}
    	return $uploadInfo;
    }
    
}

